package utils

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
)

// 加密数据
func Encrypt(data, key, iv string) (string, error) {
	aesBlockEncrypter, err := aes.NewCipher([]byte(key))
	content := PKCS5Padding([]byte(data), aesBlockEncrypter.BlockSize())
	encrypted := make([]byte, len(content))
	if err != nil {
		println(err.Error())
		return "", err
	}
	aesEncrypter := cipher.NewCBCEncrypter(aesBlockEncrypter, []byte(iv))
	aesEncrypter.CryptBlocks(encrypted, content)
	return base64.StdEncoding.EncodeToString(encrypted), nil
}

// 解密数据
func Decrypt(src, key, iv string) (data string, err error) {
	tmp, _ := base64.StdEncoding.DecodeString(src)
	ciphertext := make([]byte, len(tmp))
	var aesBlockDecrypter cipher.Block
	aesBlockDecrypter, err = aes.NewCipher([]byte(key))
	if err != nil {
		println(err.Error())
		return "", err
	}
	aesDecrypter := cipher.NewCBCDecrypter(aesBlockDecrypter, []byte(iv))
	aesDecrypter.CryptBlocks(ciphertext, []byte(tmp))
	return string(PKCS5UnPadding(ciphertext)), nil
}

//PKCS5包装

/* func PKCS5Padding(cipherText []byte, blockSize int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

//解包装

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
*/
